package com.xx.happychatboot.middleware.kaptcha.service.impl;

import cn.hutool.core.io.FastByteArrayOutputStream;
import com.google.code.kaptcha.Producer;
import com.xx.happychatboot.base.constant.RedisConstant;
import com.xx.happychatboot.base.utils.RedisUtils;
import com.xx.happychatboot.base.vo.response.ResponseDate;
import com.xx.happychatboot.middleware.kaptcha.service.KaptchaService;
import com.xx.happychatboot.middleware.kaptcha.domain.vo.response.KaptchaResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class KaptchaServiceImpl implements KaptchaService {
    @Override
    public ResponseDate getVerifyCode(HttpServletResponse response,
                                      HttpSession session, Producer producer) throws IOException {
        //1.⽣成验证码
        String code = producer.createText();
        //生成UUID和验证码绑定
        UUID randomUUID = UUID.randomUUID();
        String uuid = randomUUID.toString();
        // 使用redis存储对应的uuid和code
        RedisUtils.set(RedisConstant.KAPTCHA + uuid, code, RedisConstant.KAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);
        log.info("验证码:" + code);

        BufferedImage bi = producer.createImage(code);
        //2.写⼊内存
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fos);
        // 3.⽣成 base64
        String value = Base64.encodeBase64String(fos.toByteArray());

        KaptchaResponse kaptchaResponse = new KaptchaResponse(uuid, value);
        return ResponseDate.success("获取验证码成功", kaptchaResponse);
    }
}
